/*
 * Copyright 2010 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.kommando.web.firefox.bookmarks;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.Icon;
import javax.swing.ImageIcon;

import org.kommando.core.util.Assert;
import org.kommando.web.WebPage;

import util.Base64;

/**
 * Parses the bookmarks file.
 * 
 * @author Peter De Bruycker
 */
public class BookmarksParser {

    private static final Pattern BOOKMARK_PATTERN = Pattern.compile(".*<A .*>(.*)</A>.*", Pattern.CASE_INSENSITIVE);
    private static final Pattern HREF_PATTERN = Pattern.compile(".*HREF=\"([^\"]*)\".*");
    private static final Pattern ICON_PATTERN = Pattern.compile(".*ICON=\"([^\"]*)\".*");

    public List<WebPage> parseBookmarks(Reader reader) throws IOException {
        Assert.argumentNotNull("reader", reader);

        List<WebPage> bookmarks = new ArrayList<WebPage>();

        BufferedReader bufferedReader = new BufferedReader(reader);
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            Matcher matcher = BOOKMARK_PATTERN.matcher(line);
            if (matcher.matches()) {
                String title = matcher.group(1);
                String url = null;
                Matcher hrefMatcher = HREF_PATTERN.matcher(line);
                if (hrefMatcher.matches()) {
                    url = hrefMatcher.group(1);
                }

                Icon icon = null;

                Matcher iconMatcher = ICON_PATTERN.matcher(line);
                if (iconMatcher.matches()) {
                    String iconData = iconMatcher.group(1);

                    try {
                        icon = getFavIcon(iconData);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                WebPage webPage = new WebPage(title, url, icon);
                bookmarks.add(webPage);
            }
        }

        return bookmarks;
    }

    private static Icon getFavIcon(String iconData) throws Exception {
        Pattern dataPattern = Pattern.compile("data:image/.*;base64,(.*)");
        Matcher dataMatcher = dataPattern.matcher(iconData);
        if (dataMatcher.matches()) {
            byte[] bytes = Base64.decode(dataMatcher.group(1));

            if (bytes != null) {
                ImageInputStream imageInputStream = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes));

                Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInputStream);
                for (Iterator<ImageReader> iterator = readers; iterator.hasNext();) {
                    ImageReader imageReader = iterator.next();

                    imageReader.setInput(imageInputStream);

                    if (imageReader.getNumImages(true) > 0) {
                        try {
                            return new ImageIcon(imageReader.read(0));
                        } catch (Exception e) {
                            // TODO log exception
                        }
                    }

                    return null;
                }

            }

        }

        return null;
    }

}
